package work.chief.servlet;

import work.chief.entity.User;
import work.chief.service.UserService;
import work.chief.service.impl.UserServiceImpl;
import work.chief.utils.PageUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "userServlet",urlPatterns = "/userServlet")

public class UserServlet extends BaseServlet {
    private UserService userService =new UserServiceImpl();
    /**
     * 传参验证
     * @param request
     * @param response
     */
//    public void register(HttpServletRequest request, HttpServletResponse response){
//        System.out.println("注册");
//    }
//    public void login(HttpServletRequest request, HttpServletResponse response){
//        System.out.println("登录");
//    }

    /**
     *
     */
    public void checkedCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //输出流对象
        PrintWriter pw=response.getWriter();
        //获取前端传递的验证码
        String code=request.getParameter("code");
        //获取服务器的验证码session（键值对形式，需要强制转换）
        String sessionCode=(String)request.getSession().getAttribute("code");
        /**
         * 前端与服务器的验证码比对
         */

        boolean codeFlag=false;     //记录对比结果
        if (sessionCode.equalsIgnoreCase(code)){    //equalsIgnoreCase 忽略字符串的大小写
            codeFlag=true;
        }else {
            codeFlag=false;
        }

        pw.print(codeFlag);
        pw.close();
    }

    public void checkLogin(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        //获取前端传输的参数
        String username=request.getParameter("username");
        String password = request.getParameter("password");
        User user=userService.selectByUsernameAndPassword(username,password);
        if (user!=null){

            /**
             * 将用户信息存入session中
             */
            HttpSession session=request.getSession();
            session.setAttribute("user",user);

            //实例化servlet对象
            IndexServlet indexServlet=new IndexServlet();
            indexServlet.showInfoIndex(request, response);

            //response.sendRedirect("index.jsp");
            System.out.println("用户登录 name="+username);
        }else {
            request.setAttribute("msg","用户名或密码不正确");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }

    public void checkedPhoneNumber(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //输出流对象
        PrintWriter printWriter=response.getWriter();
        String phoneNum=request.getParameter("phoneNum");
        boolean numFlag = userService.selectByPhoneNum(phoneNum);

        //向前端打印比对结果
        printWriter.print(numFlag);

        //控制台打印结果
        //System.out.println("号码比对结果："+flag);

        printWriter.close();
    }
    public void checkedUsername(HttpServletRequest request,HttpServletResponse response) throws IOException {
        PrintWriter printWriter=response.getWriter();

        //从前端获取userName
        String username = request.getParameter("userName");
        boolean nameFlag =userService.selectByUserName((username));

        printWriter.print(nameFlag);
        printWriter.close();
    }


    /**
     * 注册功能
     * @param request
     * @param response
     * @throws Exception
     */
    public void register(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //定义一个标记记录上传状态
        boolean saveFlag=false;

        //构件一个新的User对象
        User user =new User();

        //创建一个固定文件夹保存上传的图片
        String realPath =request.getServletContext().getRealPath("/upload");
        //new一个文件对象
        File file = new File(realPath);
        //判断文件夹是否存在
        if (!file.exists()){    //不存在
            file.mkdirs();      //创建文件夹
        }
        /**
         * 判断是否是带文件的表单
         * true：带文件上床的表单
         * false：普通表单
         */
        boolean flag= ServletFileUpload.isMultipartContent(request);
        System.out.println("是否带文件表单："+flag);
        if (flag){
            //创建工厂对象
            FileItemFactory factory = new DiskFileItemFactory();
            //获取核心对象
            ServletFileUpload servletFileUpload=new ServletFileUpload(factory);
            //获取所有input标签
            List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
            //转换为迭代器
            Iterator<FileItem>iterator= fileItemList.iterator();
            //遍历
            while(iterator.hasNext()){  // iterator.hasNext()判断是否有下一个元素
                FileItem item = iterator.next();
                if(item.isFormField()){     // true : item是普通文本  false : 文件
                    String typeNmae=item.getFieldName();
                    if ("name".equals(typeNmae)) {
                        user.setName(item.getString("UTF-8"));
                    }else if ("sex".equals(typeNmae)) {

                        user.setSex(Integer.parseInt(item.getString("UTF-8")));
                    }else if ("phone_number".equals(typeNmae)) {

                        user.setPhone_number(item.getString("UTF-8"));
                    }else if ("area".equals(typeNmae)) {

                        user.setArea(item.getString("UTF-8"));
                    }else if ("username".equals(typeNmae)) {

                        user.setUsername(item.getString("UTF-8"));
                    }else if ("password".equals(typeNmae)) {

                        user.setPassword(item.getString("UTF-8"));
                    }
                }else {
                    //获取文件(item)的名字
                    String fileName=item.getName();

                    //检查拓展名判断是否为图片
                    if (fileName.endsWith("png")||fileName.endsWith("jpg")||fileName.endsWith("jpeg")||fileName.endsWith("gif")){
                        //在文件名前加上时间，保证文件唯一
                        long time=System.currentTimeMillis();
                        String newFileName=time+fileName;

                        //将文件写入服务器中
                        //暂时将名字不设置时间
                        File file1=new  File(file,fileName); //112行文件对象
                        item.write(file1);
                        user.setPhoto(fileName); //暂时不设置时间

                        saveFlag=true;
                    }else {
                        request.setAttribute("msg","文件名称不合法");
                        request.getRequestDispatcher("register.jsp").forward(request,response);
                        System.out.println("文件名称不合法");
                    }
                }
            }

            if (saveFlag){
                user.setCreate_time(new Date());
                int num=userService.register(user);
                if (num>0){
                    response.sendRedirect("login.jsp");
                    System.out.println("注册成功 "+user);
                }else {
                    request.setAttribute("mag","注册失败");

                }
            }else {
                request.setAttribute("mag","图片上传失败");
                request.getRequestDispatcher("register.jsp").forward(request,response);
                System.out.println("图片上传失败");
            }
        }else {
            request.setAttribute("mag","非正常格式");
            request.getRequestDispatcher("register.jsp").forward(request,response);
            System.out.println("非正常格式");
        }
    }


    public void adminLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        User i = userService.selectByUsernameAndPasswordAndManager(username, password, 1);
        if (i==null){

            request.setAttribute("msg","用户名或密码不正确");
            request.getRequestDispatcher("admin/login.jsp").forward(request,response);

        }else {
            request.setAttribute("user",user);
            response.sendRedirect("admin/main.jsp");
        }
    }

    public  void  showUserList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//        List<User> userList = userService.selectAll();
//        request.setAttribute("userList",userList);

        //分页查询
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr=request.getParameter("pageSize");

        Integer currentPage=null;
        if (currentPageStr==null||"".equals(currentPage)){
            currentPage=1;
        }else {
            currentPage=Integer.parseInt(currentPageStr);
        }
        Integer pageSize=null;
        if (pageSizeStr==null||"".equals(pageSizeStr)){
            pageSize=8;
        }else {
            pageSize=Integer.parseInt(pageSizeStr);
        }

        //查询
        List<User> userList = userService.selectPage(currentPage, pageSize);    //用户列表
        Integer totalPageCount = userService.selectPageCount();     //行总数

        //总页数
        Integer totalPageSize=totalPageCount%pageSize==0 ? totalPageCount/pageSize : totalPageCount/pageSize+1;

//      //写入对象
        PageUtils pageUtils=new PageUtils();
        pageUtils.setCurrentPage(currentPage);
        pageUtils.setPageSize(pageSize);
        pageUtils.setTotalPageCount(totalPageCount);
        pageUtils.setTotalPageSize(totalPageSize);
        pageUtils.setList(userList);

        request.setAttribute("pageUtils",pageUtils);

        request.getRequestDispatcher("admin/user_list.jsp").forward(request,response);
    }

    public  void changeManager(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String manager = request.getParameter("manager");
        String id = request.getParameter("id");

        userService.updateManager(Integer.parseInt(id),Integer.parseInt(manager));

        showUserList(request,response);
    }
    public void deleteUsers(HttpServletRequest request,HttpServletResponse response) throws IOException {
        PrintWriter pw= response.getWriter();

        String id = request.getParameter("id");
        int i = userService.deleteUsers(id);
        if (i>0){
            pw.print(true);
            System.out.println("成功删除了id="+id+"的用户");
        }else {
            pw.print(false);
        }
        pw.close();
    }
}